<?php


namespace App\Models\UserModels\Models;


use App\Exceptions\ApiException;
use App\Models\UserModels\UserCenterModel;

class AdminModel extends UserCenterModel
{
    public $table = 'admin';

    public $fillable = [
        'role_id',// int(11) NOT NULL DEFAULT '1' COMMENT '角色id',
        'name',// varchar(32) DEFAULT '' COMMENT '账户',
        'password',// varchar(64) DEFAULT '' COMMENT '密码',
        'member_uuid',// varchar(64) DEFAULT '' COMMENT 'uuid',
        'token',// varchar(64) DEFAULT '' COMMENT 'token',
        'member_email',// varchar(64) DEFAULT '' COMMENT '邮箱',
        'member_phone',// varchar(32) DEFAULT '' COMMENT '电话',
        'status',
        'is_delete',
        'department_id',
        'department_ids_url',
//        'create_time',// datetime DEFAULT NULL,
//        'update_time',// datetime DEFAULT NULL,
    ];

    public $hidden = ['password'];

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = md5($value);
    }

    public function getDepartmentIdsUrlAttribute($value)
    {
        return $this->strToArrayForVue($value);
    }

    public function setDepartmentIdsUrlAttribute($value)
    {
        $this->attributes['department_ids_url'] = implode(',', $value);
    }

    public function setRoleIdAttribute($value)
    {
        $this->attributes['role_id'] = implode(',', $value);
    }

    public function department()
    {
        return $this->hasOne(DepartmentModel::class,'id', 'department_id');
    }

    public function role()
    {
        return $this->hasManyFromStr(UserRoleModel::class, 'id', 'role_id');
    }

    public function userInfo()
    {
        return $this->belongsTo(UserInfoModel::class, 'id', 'account_id')
            ->withDefault();
    }

    public function getAdminList($where)
    {
        $res = $this
            ->handleCondition($where)
            ->with([
                'department:id,department',
                'role:id,role',
            ])
            ->orderBy('create_time','desc')
            ->paginate(config('pageSize'))
            ->toArray();

        return $res;

    }

    public function getAdminInfo($where)
    {
        if (empty($where))
            throw new ApiException(ApiException::ERROR_DATA_NOT_EXISTS);

        $res = $this
            ->handleCondition($where)
            ->with([
                'department',
                'role',
            ])
            ->orderBy('create_time','desc')
            ->first();

        if (is_null($res))
            throw new ApiException(ApiException::ERROR_DATA_NOT_EXISTS);


        $res->role_ids = $this->strToArrayForVue($res->role_id);

        return $res;

    }
}
